/*给你一个二元数组nums ，和一个整数goal ，请你统计并返回有多少个和为goal的非空子数组。子数组是数组的一段连续部分。
*
* 输入：nums = [1,0,1,0,1], goal = 2
* 输出：4
* 解释：如下面有 4 个满足题目要求的子数组：
* [1,0,1]
* [1,0,1]
* [0,1,0,1]
* [1,0,1,0]
* */


package Leetcode;

import java.util.HashMap;

public class leetcode930 {

    public static void main(String[] args) {

        leetcode930 obj = new leetcode930();
        int[] nums = {1, 0, 1, 0, 1};
        int goal = 2;
        System.out.println(obj.numSubarraysWithSum(nums, goal));
    }

    public int numSubarraysWithSum(int[] nums, int goal){

        int count = 0, sum = 0;
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int num: nums) {
            map.put(sum, map.getOrDefault(sum, 0) + 1);
            sum += num;
            count += map.getOrDefault(sum - goal, 0);
        }
        return count;
    }
}
